package com.bupt.ilink.entity.store;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.bupt.ilink.typehandler.JsonNodeTypeHandler;
import com.bupt.ilink.utils.JsonUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import org.apache.ibatis.type.JdbcType;

import java.util.List;

@Data
@TableName(value = "tb_store_flow", autoResultMap = true)
@SuperBuilder
@AllArgsConstructor
@NoArgsConstructor
public class StoreFlow {
    @TableId
    private String flowId;
    private String flowName;
    private String userId;
    private String userName;
    private String description;
    private Boolean shared;

    private Boolean component;
    @TableField(typeHandler = JsonNodeTypeHandler.class)
    private JsonNode data;
    private String lastTestedVersion;
    @TableField(typeHandler = JsonNodeTypeHandler.class)
    private JsonNode metaData;

    public void selfGenerateMetaData() {
        metaData = getMetaData();
    }

    public JsonNode getMetaData() {
        if (metaData == null && data != null) {
            metaData = extractMetaData();
        }
        return metaData;
    }

    private JsonNode  extractMetaData() {
        JsonNode nodes = data.get("nodes");
        ObjectNode metaData = JsonUtils.createObjectNode();
        for (JsonNode node : nodes) {
            String type = node.get("data").get("type").asText();
            int count = metaData.has(type) ? metaData.get(type).asInt() : 0;
            ObjectNode countNode = JsonUtils.createObjectNode();
            countNode.put(   "count", count + 1);
            metaData.set(type, countNode);
        }
        metaData.put("total", nodes.size());
        return metaData;
    }
}
